<?php

namespace App\Services\Admin;

use App\Enums\AdminUserTypeEnum;
use App\Exceptions\AdminException;
use App\Managers\Admin\AdminUsersManager;
use App\Models\AdminGroupModel;
use App\Models\AdminUsers;
use App\Models\AdminUsersModel;
use App\Services\BaseService;
use App\Util\LoginUtil;
use Illuminate\Support\Facades\Hash;
use Rocky\DataCenterClient\Application;

class AdminUsersService extends BaseService
{
    public function __construct(AdminUsersManager $model)
    {
        parent::__construct();
        $this->manager = $model;
    }


    /** 新组织创建第一个角色 */
    public function createFirstUsers()
    {
        $group_id = $this->getData('group_id');
        $role_id = $this->getData('role_id');
        $account = $this->getData('account');
        $name = $this->getData('name');
        $phone = $this->getData('phone');


        //检查是否存在
        $id = AdminUsersModel::query()->where('group_id', $group_id)->value('id');
        if (empty($id)) {
            $this->manager->setData([
                'group_id' => $group_id,
                'account' => $account,
                'name' => $name,
                'phone' => $phone,
                'password_confirm' => md5("123456"),
                'role_id' => $role_id,
                'password' => md5("123456"),

            ])->save();
            $id = $this->manager->getData('id');
        }

        return $id;
    }

    public function modifyPassword()
    {
        $user_id = LoginUtil::getUserId();
        $this->setData([
            'id' => $user_id,
            'updated_by_admin_id' => $user_id,
            'password' => $this->getData('password'),
            'password_confirm' => $this->getData('password_confirm')
        ]);
        return $this->save();
    }

    public function modifyPayPassword()
    {
        /** @var AdminUsers $user **/
        $user = LoginUtil::getUserInfo('', 'admin');
        $payPassword = $this->getData('pay_password');
        $adminGroup = AdminGroupModel::whereId($user->group_id)->first();
//        $user = AdminUsersModel::whereId($user->id)->first();
//        $role = $user->role_info;
        if (empty($adminGroup)) {
            return false;
        }
        $captcha = $this->getData('captcha');
        $captchaRes = mobileCaptcha($user->phone, $captcha);
        if (!$captchaRes) {
            throw new AdminException('验证码错误');
        }
        $paySalt = Hash::make($payPassword);
        $salt = $paySalt . config("app.salt");
        $payPassword = md5(sha1($payPassword . $salt));

        $adminGroup->update([
            'pay_password' => $payPassword,
            'pay_salt' => $paySalt,
        ]);
        return true;
    }

    public function captcha()
    {
        /** @var AdminUsers $user **/
        $user = LoginUtil::getUserInfo('', 'admin');
        return mobileCaptcha($user->phone);
    }

    /**
     * 获取当前管理员信息
     * @param array $field 获取字段
     * @return mixed
     */
    public function getManageInfo($field = ['*'])
    {
        return $this->manager->getManageInfo($field);
    }


    public function setPower()
    {
        /** @var AdminMenuService $app */
        $app = app(AdminMenuService::class);
        return $app->setPower($this->data);
    }

    public function setRoutes()
    {
        /** @var AdminRoutesService $app */
        $app = app(AdminRoutesService::class);
        return $app->setRoutes($this->data);
    }

    public function tempGroup()
    {
        $user_id = LoginUtil::getUserId();
        $this->setData(['id' => $user_id, 'temp_group_id' => $this->getData('temp_group_id')]);
        return $this->save();
    }

    public function lists($isPage = true)
    {

        $admin_info = LoginUtil::getUserInfo();
        $admin_user_type = data_get($admin_info, 'user_type', 0);
        $admin_id = data_get($admin_info, 'id');
        $is_open = data_get($admin_info, 'is_open');
        if ($is_open !== 0 && $admin_user_type !== AdminUserTypeEnum::SYSTEMADMIN) {
            $this->setData('id', $admin_id);
        }

        return parent::lists($isPage);
    }

    public function getGroupAllAdmin()
    {
        $group_id = $this->getData('group_id', 0);
        $model = AdminUsersModel::query();
        $model->with(['getGreatedByUserInfo' => function ($build) {
            $build->select(['id', 'account']);
        }]);
        $model->with(['role_info' => function ($build) {
            $build->select(['admin_user_id', 'role_id']);
        }]);
        return $model->where('group_id', $group_id)->orWhere('guards', 'master')->get()->toArray();
    }

    /**
     * 验证支付密码
     *
     * */
    public function verifyPayPassword()
    {
        /** @var AdminUsers $user **/
        $user = \Auth::user();
        $group = $user->myGroup;
        $pay_password = $this->getData('pay_password');
        $salt = $group->pay_salt . config('app.pay_salt');
        return md5(sha1($pay_password . $salt)) == $group->pay_password;
    }

    public function SyncDataCenterUsers()
    {
        $admin_info = LoginUtil::getUserInfo();
        $admin_user_type = data_get($admin_info, 'user_type', 0);
        if ($admin_user_type != 1) return;
        $admin_list = AdminUsersModel::query()->select(['id','account','phone','user_type','is_valid'])->where(['guards'=>'master','is_valid'=>1])->where('data_center_admin_user_id','=',null)->get()->toArray();
        $config = config('data_center');
        $app = Application::make($config);

        foreach ($admin_list as $v){
            $account = data_get($v,'account','');
            $phone = data_get($v,'phone','');
            $password = 123456;
            if (!empty($account) && !empty($phone)){
                $info = $app->user->create($phone,$account,$password);
                $data_center_admin_user_id = data_get($info,'id','');
                if (!empty($data_center_admin_user_id)) AdminUsersModel::query()->where(['id'=>data_get($v,'id',0)])->update(['data_center_admin_user_id'=>$data_center_admin_user_id]);
            }
        }
        return [];
    }
}
